<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="一步一步跟我学设计模式, 一只帅帅的猿儿">
    <meta name="description" content="其实这个世界上大部分传奇，不过是普普通通的人们将心意化成了行动，坚持至极致而已!">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>一步一步跟我学设计模式 | 一只帅帅的猿儿</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 4.2.0"><link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" style="height: 40px;line-height: 36px; background-image: linear-gradient(to right, #7b99de 0%, #120f69 100%);" class="nav-transparent">
        <div id="navContainer" class="nav-wrapper container"  >
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" style="height: 37px;
    vertical-align: middle;
     padding-bottom: 0px;" alt="LOGO">
                    
                    <span class="logo-span" style="font-size: 1.5rem;">一只帅帅的猿儿</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">一只帅帅的猿儿</div>
        <div class="logo-desc">
            
            其实这个世界上大部分传奇，不过是普普通通的人们将心意化成了行动，坚持至极致而已!
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://gitee.com/LiJianGit/" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://gitee.com/LiJianGit/" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/11.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">一步一步跟我学设计模式</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/java/">
                                <span class="chip bg-color">java</span>
                            </a>
                        
                            <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">
                                <span class="chip bg-color">设计模式</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/" class="post-category">
                                架构设计
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-03-06
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2020-03-06
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    6.7k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    27 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>

        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>设计模式 是前辈积累总结下来的最佳实践技巧，随着我们的开发经验的提高，设计模式成为划分开发水平的标准之一。简单而言：设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。</p>
<h2 id="第-1-章-什么是设计模式？"><a href="#第-1-章-什么是设计模式？" class="headerlink" title="第 1 章 什么是设计模式？"></a>第 1 章 什么是设计模式？</h2><h3 id="1-1-为什么要学习设计模式？"><a href="#1-1-为什么要学习设计模式？" class="headerlink" title="1.1 为什么要学习设计模式？"></a>1.1 为什么要学习设计模式？</h3><p><strong>设计模式</strong> ( design pattern ) 是对面向对象设计中反复出现的问题的解决方案。这里要注意：算法不是设计模式，因为算法致力于解决问题而非设计问题。设计模式通常描述了一组相互紧密作用的类与对象。它提供一种讨论软件设计的公共语言，使得熟练设计者的设计经验可以被初学者和其他设计者掌握。设计模式还为软件重构提供了目标。 </p>
<p><strong>总结：</strong> 要想你写出来的大神级别的漂亮代码，具有 <strong>高内聚</strong>、<strong>低耦合</strong>的特点，学好 <strong>设计模式</strong> 是你必须要做的，譬如：要想吃中餐，就要学使用筷子这一技能。</p>
<h2 id="第-2-章-UML-类图的初步入门"><a href="#第-2-章-UML-类图的初步入门" class="headerlink" title="第 2 章 UML 类图的初步入门"></a>第 2 章 UML 类图的初步入门</h2><h3 id="2-1-什么是-UML-类图"><a href="#2-1-什么是-UML-类图" class="headerlink" title="2.1 什么是 UML 类图"></a>2.1 什么是 UML 类图</h3><p><strong>统一建模语言</strong>（ Unified Modeling Language，UML ）又称标准建模语言，是始于 1997 年的一个 OMG 标准，它是一个支持模型化和软件系统开发的图形化语言，为软件开发的所有阶段提供模型化和可视化支持，包括由需求分析到规格，到构造和配置。</p>
<h3 id="2-2-UML-的分类"><a href="#2-2-UML-的分类" class="headerlink" title="2.2  UML 的分类"></a>2.2  UML 的分类</h3><p>UML 从考虑系统的不同角度出发，定义了 <strong>用况图</strong>、<strong>类图</strong>、<strong>对象图</strong>、<strong>包图</strong>、<strong>状态图</strong>、<strong>活动图</strong>、<strong>序列图</strong>、<strong>通信图</strong>、<strong>构件图</strong>、<strong>部署图</strong> 等10种图。在这这里我们通过 <strong>UML 的类图</strong> 的学习可以快速方便我们更好的入门和掌握设计模式。<br>其他种类的 UML 图请自行问 谷歌哥哥，百度姐姐。</p>
<h3 id="2-3-UML-类图初步入门"><a href="#2-3-UML-类图初步入门" class="headerlink" title="2.3 UML 类图初步入门"></a>2.3 UML 类图初步入门</h3><p><strong>什么是UML 类图？</strong><br>回答：用于表示类、接口、实例等之间相互静态关系的图。<br><img src="https://images.gitbook.cn/4f9e1f40-4667-11ea-b5fc-c30e6f2b5954" alt="在这里插入图片描述"><br>|      | 归纳 |<br>|:———-:| :————-:|<br>| 第 1 点 |  <strong>Student</strong> 表示类名，<strong><em>Student</em></strong>  斜体表示抽象类，类上方加 &lt;&lt;<strong>interface</strong>&gt;&gt; 表示接口 |<br>| 第 2 点 | <strong>+</strong> 代表 <strong>public</strong> ;  <strong>-</strong> 代表  <strong>private</strong> ;  <strong>#</strong> 代表 <strong>protected</strong> ;  <strong>~</strong>  代表 <strong>default</strong>  |<br>|  第 3 点 | 属性或者方法下面加横线表示 <strong>static</strong>  |<br>|  第 4 点 | 方法 <em>study()</em> 为斜体，表示为抽象方法。   |</p>
<h4 id="2-3-1-继承或者实现"><a href="#2-3-1-继承或者实现" class="headerlink" title="2.3.1 继承或者实现"></a>2.3.1 继承或者实现</h4><blockquote>
<p>UML 箭头方向：从子类指向父类</p>
</blockquote>
<p>类的继承和实现 UML 图：<strong>实线 | 虚线 + 空心三角箭头</strong>。</p>
<ol>
<li><strong>实线</strong> 代表的是继承 ( extends ) 关系，它是 is - a 的关系。</li>
<li><strong>虚线</strong> 代表的是实现 (implements) 的关系，它是 can - do 的关系</li>
<li><strong>空心三角箭头</strong>：继承或者实现,如下图红框所示。<br><img src="https://images.gitbook.cn/0a944120-4669-11ea-8bef-d7e4fe1dc66a" alt="在这里插入图片描述"></li>
</ol>
<h4 id="2-3-2-关联与依赖"><a href="#2-3-2-关联与依赖" class="headerlink" title="2.3.2 关联与依赖"></a>2.3.2 关联与依赖</h4><p>注意此时的箭头不同于空心三角形。 箭头方向指向被依赖或者被关联的对象。<br>1、<strong>实线 代表 关联关系：</strong> 表示一个类对象和另外一个类对象有关联通常是一个类中有另一个类对象作为属性<br>2、<strong>虚线 代表 依赖关系：</strong> 表示一种使用关系，一个类需要借助另一个类来实现功能，一般是一个类使用另一个类作为入参或者返回值，只有调用某个方法时才会使用<br><img src="https://images.gitbook.cn/87c13cc0-4669-11ea-814b-0d3e32b9c16f" alt="在这里插入图片描述"></p>
<h4 id="2-3-3-组合与聚合"><a href="#2-3-3-组合与聚合" class="headerlink" title="2.3.3 组合与聚合"></a>2.3.3 组合与聚合</h4><p>1、<strong>实心菱形 代表 组合关系：</strong> 强关系（鸟和翅膀），组合在一起，箭头指的是组件（翅膀），两者拥有相同的生命周期，contains-a的关系，为强关系。<br>2、<strong>空心菱形 代表 聚合关系：</strong> 相同的东西聚在一起（大雁群和大雁的关系），箭头所指的类为个体（大雁），整体和局部的关系，二者具体独立的生命周期，has-a的关系，为弱关系。<br><img src="https://images.gitbook.cn/1c519dd0-466a-11ea-8bef-d7e4fe1dc66a" alt="在这里插入图片描述"><br>本节最后，以动物为例，附带一张 UML 完整的类图。图片来源于：&lt;&lt;大话设计模式&gt;&gt;<br><img src="https://images.gitbook.cn/55318d90-466a-11ea-8bef-d7e4fe1dc66a" alt="在这里插入图片描述"></p>
<h2 id="第-3-章-设计模式的分类"><a href="#第-3-章-设计模式的分类" class="headerlink" title="第 3 章 设计模式的分类"></a>第 3 章 设计模式的分类</h2><p>接下来，通过两张图片大致看一下设计模式的几种类型，以及设计模式之间的关系。<br><img src="https://images.gitbook.cn/408de870-4ccd-11ea-9f6e-1bdc6229ab3f" alt="在这里插入图片描述"><br><img src="https://images.gitbook.cn/42fe2fb0-4cce-11ea-8823-b14c07bf0c6c" alt="设计模式之间的关系"><br>言归正传，从本章开始，跟着我的脚步，一步一步学习设计模式。</p>
<h3 id="3-1-单例模式"><a href="#3-1-单例模式" class="headerlink" title="3.1 单例模式"></a>3.1 单例模式</h3><h4 id="3-1-1-什么是单例？"><a href="#3-1-1-什么是单例？" class="headerlink" title="3.1.1 什么是单例？"></a>3.1.1 <strong>什么是单例？</strong></h4><p><strong>单例模式</strong> 属于创建类型的一种常用的软件设计模式。也叫单态模式，是 java 程序员面试常问的设计模式之一。单例模式在整个程序的运行中只允许有一个类的实例，不管 new 多少次，它总是相等的。</p>
<h4 id="3-1-2-单例模式的常用的应用场景"><a href="#3-1-2-单例模式的常用的应用场景" class="headerlink" title="3.1.2 单例模式的常用的应用场景"></a>3.1.2 <strong>单例模式的常用的应用场景</strong></h4><p>a、需要频繁实例化然后销毁的对象。<br>b、创建对象是耗时过多或者消耗资源过多，但程序还经常用到的对象。</p>
<h4 id="3-1-3-单例模式的实现步骤"><a href="#3-1-3-单例模式的实现步骤" class="headerlink" title="3.1.3 单例模式的实现步骤"></a>3.1.3 <strong>单例模式的实现步骤</strong></h4><ul>
<li>类的构造方法必须进行私有化，不对外开放。构造函数访问修饰符为 <strong>private</strong> 。</li>
<li>对象实例必须是一个而且是唯一一个，类必须加上 <strong>static</strong> 修饰。</li>
<li>类对外应需提供获取该类实例的公有方法，方法必须也是 <strong>static</strong> 修饰。</li>
</ul>
<h4 id="3-1-4-单例模式的实现方式"><a href="#3-1-4-单例模式的实现方式" class="headerlink" title="3.1.4 单例模式的实现方式"></a>3.1.4 <strong>单例模式的实现方式</strong></h4><p><img src="https://images.gitbook.cn/c4e776b0-4cd5-11ea-bb35-2725b4649300" alt="在这里插入图片描述"><br><strong>第 1 种：饿汉式</strong><br><img src="https://images.gitbook.cn/7f7ad490-4cd6-11ea-a325-5b2189984a9b" alt="在这里插入图片描述"></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SingletonDemo1</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token keyword">static</span> SingletonDemo1 instance <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SingletonDemo1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token function">Singleton1</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> Singleton1 <span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> instance<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>巧记</strong> ：我很饿，我想吃的时候，你已经给我做好准备让我吃了。<br><strong>不足：</strong> 不能延迟加载。一上来就实例化对象，如果程序从不调用它，资源上的浪费</p>
<p><strong>第 2 种：懒汉式</strong><br><img src="https://images.gitbook.cn/54386290-4ce3-11ea-bb35-2725b4649300" alt="在这里插入图片描述"><br>线程不安全的懒汉式：</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SD2</span> <span class="token punctuation">{</span>

    <span class="token comment" spellcheck="true">//类初始化时，不初始化这个对象(延时加载，真正用的时候再创建)</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> SD2 instance<span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token function">SD2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span><span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> SD2 <span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">// 这里会出现线程不安全,解决方法 同步代码块 或者 同步方法。</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>instance<span class="token operator">==</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            instance<span class="token operator">=</span><span class="token keyword">new</span> <span class="token class-name">SD2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> instance<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>以同步方法实现懒汉式线程安全为例，代码如下：</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SD2Syn</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token keyword">static</span> SD2Syn instance<span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token function">SD2Syn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span><span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> synchronized SD2Syn <span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>instance<span class="token operator">==</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            instance<span class="token operator">=</span><span class="token keyword">new</span> <span class="token class-name">SD2Syn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> instance<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>巧记</strong> ：我很懒，我先拖着，需要的时候再弄吧。</p>
<p><strong>第 3 种：双重锁判断机制 DCL</strong> 不建议使用<br><img src="https://images.gitbook.cn/423235b0-4ce5-11ea-a2a8-bf3f3a718133" alt="在这里插入图片描述"><br>因为存在指令重排的问题，所以这里实例必须为 <strong>volatile</strong> 避免指令重排。</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SD3</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> volatile <span class="token keyword">static</span> SD3 instance<span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token function">SD3</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> SD3 <span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>instance <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            synchronized <span class="token punctuation">(</span>SD3<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>instance <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    instance <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SD3</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> instance<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>巧记</strong> ：它就是懒加载的升级版，双重验证 + volatile 。<br><strong>不足</strong> ：使用的时候需要加 volatile ，以免造成虚拟机的指令重排而导致失败。</p>
<p><strong>第 4 种：静态内部类</strong>  推荐建议<br><img src="https://images.gitbook.cn/95fbaef0-4ce6-11ea-9aca-f5e54cebdcef" alt="在这里插入图片描述"></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SD4</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token function">SD4</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

    <span class="token keyword">public</span> SD4 <span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> SingletonHolder4<span class="token punctuation">.</span>SINGLETON<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">SingletonHolder4</span> <span class="token punctuation">{</span>
        <span class="token keyword">private</span> <span class="token keyword">static</span> final SD4 SINGLETON <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SD4</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>不足</strong> ：它已经是最完美了，如果非要鸡蛋里挑骨头的话，那就是不能防止反射或者反序列化的调用。</p>
<p><strong>第 5 种：枚举类</strong><br>枚举类是 Java 之父 写出来的一种单例模式。默认枚举实例的创建时线程安全的，且在任何一种情况下它都是单例的，所以它很好的防止反序列化或者反射的调用。<br><img src="https://images.gitbook.cn/61973fc0-4ce7-11ea-bb35-2725b4649300" alt="在这里插入图片描述"></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">enum</span> SD5 <span class="token punctuation">{</span>
    INSTANCE<span class="token punctuation">;</span>

    <span class="token keyword">public</span> SD5 <span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> INSTANCE<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>不足</strong> ：它不能延迟加载。</p>
<hr>
<p><strong>总结：</strong><br><img src="https://images.gitbook.cn/faeffe50-4ce7-11ea-aeb5-6d255c028296" alt="在这里插入图片描述"><br>条件     | 结果<br>——– | —–<br>单例对象 占用资源少，不需要延时加载  | 枚举 &gt; 饿汉<br>单例对象 占用资源多，需要延时加载  | 静态内部类 &gt; 懒汉式</p>
<h3 id="3-2-工厂模式"><a href="#3-2-工厂模式" class="headerlink" title="3.2 工厂模式"></a>3.2 工厂模式</h3><p>本博客采用 Java 语言实现相关的工厂代码。<br><img src="https://images.gitbook.cn/507ae130-4cea-11ea-bb27-bdb4967fc6e0" alt="在这里插入图片描述"></p>
<h4 id="3-2-1-简单工厂模式"><a href="#3-2-1-简单工厂模式" class="headerlink" title="3.2.1 简单工厂模式"></a>3.2.1 简单工厂模式</h4><blockquote>
<p>简单工厂并不属于 23 中常用模式。</p>
</blockquote>
<p><strong>什么是简单工厂？</strong><br>简单工厂模式属于创建型模式，又叫做静态工厂方法模式。它来负责创建其他类的实例，被创建的实例通常都具有共同的父类。简而言之，简单工厂模式就是一个专门生产某产品的类。比如：富士康造手机，伊利奶厂造不同型号的奶等等。<br><img src="https://images.gitbook.cn/1bec1350-466c-11ea-b5fc-c30e6f2b5954" alt="在这里插入图片描述"><strong>简单工厂的代码实现</strong></p>
<blockquote>
<p>例子：以手机制造为例，富士康就是我们的手机工厂，<br>它可以根据传入代号或者型号来分别生产Phone、HuaWei等手机。</p>
</blockquote>
<ol>
<li><p>定义手机抽象类。</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> abstract <span class="token keyword">class</span> <span class="token class-name">Phone</span> <span class="token punctuation">{</span>
 <span class="token keyword">public</span> abstract <span class="token keyword">void</span> <span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<ol start="2">
<li><p>各大手机制造商制造他们手机的流程步骤。</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ApplePhone</span> <span class="token keyword">extends</span> <span class="token class-name">Phone</span> <span class="token punctuation">{</span>

@Override
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"我被制造出来了！我是苹果手机"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">HuaWeiPhone</span> <span class="token keyword">extends</span> <span class="token class-name">Phone</span> <span class="token punctuation">{</span>

@Override
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"我被制造出来了！我是华为手机"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">OppoPhone</span> <span class="token keyword">extends</span> <span class="token class-name">Phone</span> <span class="token punctuation">{</span>

@Override
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"我被制造出来了！我是Oppo手机"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
</li>
<li><p>定义一个手机制造工厂，比如富士康一样的公司工厂。</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">PhoneFactory</span> 
<span class="token comment" spellcheck="true">/**
* 第一种：这里是通过 if-else 实现的简单工厂模式
*/</span>
<span class="token keyword">public</span> Phone <span class="token function">create</span><span class="token punctuation">(</span>int type<span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>type <span class="token operator">==</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">ApplePhone</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>type <span class="token operator">==</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">HuaWeiPhone</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>type <span class="token operator">==</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">OppoPhone</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">/**
* 第二种：这里也可以通过反射实现的简单工厂 推荐使用
*/</span>
<span class="token keyword">public</span> Phone <span class="token function">create</span><span class="token punctuation">(</span>Class <span class="token class-name">clazz</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
 Phone phone <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
  <span class="token keyword">try</span> <span class="token punctuation">{</span>
      phone <span class="token operator">=</span> <span class="token punctuation">(</span>Phone<span class="token punctuation">)</span> Class<span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span>clazz<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InstantiationException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IllegalAccessException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ClassNotFoundException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">return</span> phone<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>最后，工厂制造的过程（客户端调用）</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TestClient</span> <span class="token punctuation">{</span>

<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  PhoneFactory phoneFactory <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">PhoneFactory</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment" spellcheck="true">/* 通过 if-else 实现的简单工厂模式 */</span>
  Phone phone <span class="token operator">=</span> phoneFactory<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  phone<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment" spellcheck="true">/* class 通过反射 实现的简单工厂 */</span>
  Phone phone1 <span class="token operator">=</span> phoneFactory<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span>OppoPhone<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  phone1<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</li>
</ol>
</li>
</ol>
<pre><code>
通过实例去分析：**简单工厂模式的缺点在于**：当每次新增一个手机新品牌的时候，我们必须在要修改工厂类的生产方法，在工厂类中增加对应的判断分支，所以这样违背了我们所说的 **开放封闭原则**。
&gt;开放封闭原则（OCP，Open Closed Principle）是所有面向对象原则的核心。软件设计本身所追求的目标就是封装变化、降低耦合，而开放封闭原则正是对这一目标的最直接体现。

**总结：** 
![简单工厂的总结](https://images.gitbook.cn/d38b8370-4cec-11ea-bea2-9fad8905a8df)

#### 3.2.2 工厂方法模式
&gt;工厂方法模式 是解决 简单工厂模式 违背 **开放封闭原则** 问题的一种解决方式。

这里以 **加减乘除** 运算为例来实现一个运算工厂

1. 首先，定义一个运算的接口。
```javascript
public interface Operation {
    double result(double firstNum,double secondNum) throws Exception;
}</code></pre><p>2.分别创建加减乘除类从而实现加减乘除的运算功能。</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * 加法实现类
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">AddNum</span> <span class="token keyword">implements</span> <span class="token class-name">Operation</span><span class="token punctuation">{</span>
    @Override
    <span class="token keyword">public</span> double <span class="token function">result</span><span class="token punctuation">(</span>double firstNum<span class="token punctuation">,</span>double secondNum<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> firstNum <span class="token operator">+</span> secondNum<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * 减法实现类
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SubNum</span> <span class="token keyword">implements</span> <span class="token class-name">Operation</span><span class="token punctuation">{</span>
    @Override
    <span class="token keyword">public</span> double <span class="token function">result</span><span class="token punctuation">(</span>double firstNum<span class="token punctuation">,</span>double secondNum<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> firstNum <span class="token operator">-</span> secondNum<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * 乘法实现类
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MulNum</span> <span class="token keyword">implements</span> <span class="token class-name">Operation</span><span class="token punctuation">{</span>
    @Override
    <span class="token keyword">public</span> double <span class="token function">result</span><span class="token punctuation">(</span>double firstNum<span class="token punctuation">,</span>double secondNum<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> firstNum <span class="token operator">*</span> secondNum<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>除法相关</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * 除法实现类
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DivNum</span> <span class="token keyword">implements</span> <span class="token class-name">Operation</span><span class="token punctuation">{</span>
    @Override
    <span class="token keyword">public</span> double <span class="token function">result</span><span class="token punctuation">(</span>double firstNum<span class="token punctuation">,</span>double secondNum<span class="token punctuation">)</span> throws Exception <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>secondNum <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">Exception</span><span class="token punctuation">(</span><span class="token string">"除数不能为0！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> firstNum <span class="token operator">/</span> secondNum<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<ol start="3">
<li>分别对 加减乘除 工厂类的实现 </li>
</ol>
<p>步骤：定义工厂接口，创建 加减乘除 四个工厂实现方法</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * 定义工厂接口
 */</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">OperationFactory</span> <span class="token punctuation">{</span>
    Operation <span class="token function">initOperation</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * 加法工厂类
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">AddFactory</span> <span class="token keyword">implements</span> <span class="token class-name">OperationFactory</span> <span class="token punctuation">{</span>
    @Override
    <span class="token keyword">public</span> Operation <span class="token function">initOperation</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">AddNum</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * 减法工厂类
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SubFactory</span> <span class="token keyword">implements</span> <span class="token class-name">OperationFactory</span> <span class="token punctuation">{</span>
    @Override
    <span class="token keyword">public</span> Operation <span class="token function">createOperation</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">SubNum</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<ol start="4">
<li>客户端调用</li>
</ol>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TestClient</span> <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            OperationFactory addFactory <span class="token operator">=</span> <span class="token punctuation">(</span>OperationFactory<span class="token punctuation">)</span> Class<span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span>AddFactory<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            Operation operation <span class="token operator">=</span> addFactory<span class="token punctuation">.</span><span class="token function">createOperation</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            double result <span class="token operator">=</span> operation<span class="token punctuation">.</span><span class="token function">result</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InstantiationException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IllegalAccessException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ClassNotFoundException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<h4 id="3-2-3-抽象工厂的实现"><a href="#3-2-3-抽象工厂的实现" class="headerlink" title="3.2.3 抽象工厂的实现"></a>3.2.3 <strong>抽象工厂的实现</strong></h4><p>工厂方法模式是工厂只生产一种产品，就是 OperationFactory 接口只有一个抽象方法， 当工厂生产至少 2 种产品的话，那么此工厂成为 抽象工厂。</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">CreateFactory</span> <span class="token punctuation">{</span>
    Phone <span class="token function">createPhone</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">;</span>
    Pad <span class="token function">cratePad</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>总结：</strong><br><img src="https://images.gitbook.cn/8eafa700-4d9a-11ea-a221-c1e42d9b4512" alt="在这里插入图片描述"></p>
<h4 id="3-2-4-工厂模式与抽象工厂模式不同点"><a href="#3-2-4-工厂模式与抽象工厂模式不同点" class="headerlink" title="3.2.4 工厂模式与抽象工厂模式不同点"></a>3.2.4 工厂模式与抽象工厂模式不同点</h4><p><img src="https://images.gitbook.cn/f7803ba0-4d9a-11ea-a2a8-bf3f3a718133" alt="在这里插入图片描述"><br><img src="https://img-blog.csdnimg.cn/20200106143150629.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2ppYW5saTk1,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<h4 id="3-2-5-举例子加深印象"><a href="#3-2-5-举例子加深印象" class="headerlink" title="3.2.5 举例子加深印象"></a>3.2.5 举例子加深印象</h4><p>本例子以种菜为例，详细看下图的UML图。<br><strong>简单工厂模式UML图</strong><br><img src="https://images.gitbook.cn/4a101910-466d-11ea-936b-cfa88a589a44" alt="在这里插入图片描述"><br><strong>工厂方法模式UML图</strong><br><img src="https://images.gitbook.cn/502eb7c0-466d-11ea-895e-2fe851c47874" alt="在这里插入图片描述"><br><strong>抽象工厂方法UML图</strong><br><img src="https://images.gitbook.cn/58b2e4c0-466d-11ea-815b-99042f14883a" alt="在这里插入图片描述"><br>在CSDN还看到一篇很好的例子：<a href="https://blog.csdn.net/u013759988/article/details/82383077" target="_blank" rel="noopener">饺子-包子设计模式</a></p>
<h3 id="3-3-原型模式"><a href="#3-3-原型模式" class="headerlink" title="3.3 原型模式"></a>3.3 原型模式</h3><p><strong>什么是原型（Prototype）模式？</strong> </p>
<p><strong>原型模式：</strong>   用一个已经创建的实例作为原型，通过复制该原型对象来创建一个和原型相同或相似的新对象。就是我们所理解的 <strong>克隆</strong> 对象。用这种方式创建对象非常高效，根本无须知道对象创建的细节。如果创建一个新的对象，消耗的时间是相对长的，不如我们可以用原型模式，然后对对象进行复制。</p>
<p><strong>大致步骤讲解：</strong><br>先 <strong>实现 Cloneable 接口</strong>  后 <strong>重写 clone() 方法</strong> 。</p>
<blockquote>
<p>原型模式的克隆分为 <strong>浅克隆</strong> 和 <strong>深克隆</strong>，Java 中的 Object 类提供了浅克隆的 clone() 方法，具体原型类只要实现 Cloneable 接口就可实现对象的浅克隆，这里的 Cloneable 接口就是抽象原型类。其代码如下：</p>
</blockquote>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Draw</span> <span class="token keyword">implements</span> <span class="token class-name">Cloneable</span>  <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token function">Draw</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"我已经画好了《蒙娜丽莎》。"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    @Override
    <span class="token keyword">protected</span> Object <span class="token function">clone</span><span class="token punctuation">(</span><span class="token punctuation">)</span> throws CloneNotSupportedException <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token keyword">super</span><span class="token punctuation">.</span><span class="token function">clone</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<p>客户端调用</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TestClient</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> throws CloneNotSupportedException <span class="token punctuation">{</span>
        Draw draw <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Draw</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        Draw clone <span class="token operator">=</span> <span class="token punctuation">(</span>Draw<span class="token punctuation">)</span> draw<span class="token punctuation">.</span><span class="token function">clone</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"两个对象是否相同："</span><span class="token operator">+</span><span class="token punctuation">(</span>draw <span class="token operator">==</span> clone<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<p><img src="https://images.gitbook.cn/b0efda30-466d-11ea-936b-cfa88a589a44" alt="在这里插入图片描述"><br><strong>注意：</strong> 原型模式 克隆后的对象与原来对象 <strong>不相同</strong>，默认为 <strong>浅克隆</strong>，<strong>深克隆</strong> 请重写 clone() 方法。</p>
<h3 id="3-4-建造者模式"><a href="#3-4-建造者模式" class="headerlink" title="3.4 建造者模式"></a>3.4 建造者模式</h3><h4 id="3-4-1-什么是建造者模式？"><a href="#3-4-1-什么是建造者模式？" class="headerlink" title="3.4.1 什么是建造者模式？"></a>3.4.1 什么是建造者模式？</h4><p>将一个复杂对象的构造与它的表示分离，使同样的构建过程可以创建不同的表示，这样的设计模式被称为建造者模式。例如电脑组装相关，房子布局等。</p>
<h4 id="3-4-2-建造者中相关的角色"><a href="#3-4-2-建造者中相关的角色" class="headerlink" title="3.4.2 建造者中相关的角色"></a>3.4.2 建造者中相关的角色</h4><ol>
<li>建造者（Builder）：为创建一个产品对象的各个部件指定抽象接口。</li>
<li>具体建造者（ConcreteBuilder）：实现Builder的接口以构造和装配该产品的各个部件，定义并明确它所创建的表示，并 提供一个检索产品的接口。</li>
<li>指挥者（Director）：指挥并构造一个使用Builder接口的对象。</li>
<li>产品（Product）：表示被构造的复杂对象。ConcreteBuilder创建该产品的内部表示并定义它的装配过程，包含定义组成部件的类，包括将这些部件装配成最终产品的接口。</li>
</ol>
<h4 id="3-4-3-建造者相关代码的实现"><a href="#3-4-3-建造者相关代码的实现" class="headerlink" title="3.4.3 建造者相关代码的实现"></a>3.4.3 建造者相关代码的实现</h4><blockquote>
<p>本文以 <strong>组装计算机</strong> 为例,</p>
</blockquote>
<p><strong>1.编写产品</strong></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * @author jian.li
 * @date 2020年 01月06日 16:09:36
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Computer</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">/* CPU的型号 */</span>
    <span class="token keyword">private</span> String CPU<span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">/*  固态的型号 */</span>
    <span class="token keyword">private</span> String SSD<span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">/* 内存型号 */</span>
    <span class="token keyword">private</span> String RAM<span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">/* 硬盘型号 */</span>
    <span class="token keyword">private</span> String ROM<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">// getter or setter 已经省略</span>
    @Override
    <span class="token keyword">public</span> String <span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">"我组装了一个电脑，配置如下：{CPU='"</span> <span class="token operator">+</span> CPU <span class="token operator">+</span> <span class="token string">", SSD='"</span> <span class="token operator">+</span> SSD <span class="token operator">+</span> <span class="token string">", RAM='"</span> <span class="token operator">+</span> RAM <span class="token operator">+</span> <span class="token string">", ROM='"</span> <span class="token operator">+</span> ROM <span class="token operator">+</span> <span class="token string">'}'</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>2.建造者的代码</strong> 建造者为抽象类， 里面包括 computer 属性，并提供相关的组装计算机的抽象方法。</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * @author jian.li
 * @date 2020年 01月06日 16:17:10
 */</span>
<span class="token keyword">public</span> abstract <span class="token keyword">class</span> <span class="token class-name">ComputerBuilder</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> Computer computer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Computer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/* 组装CPU */</span>
    <span class="token keyword">public</span> abstract <span class="token keyword">void</span> <span class="token function">CPU</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">/* 组装固态硬盘 */</span>
    <span class="token keyword">public</span> abstract <span class="token keyword">void</span> <span class="token function">SSD</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">/* 组装内存 */</span>
    <span class="token keyword">public</span> abstract <span class="token keyword">void</span> <span class="token function">RAM</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">/* 组装硬盘 */</span>
    <span class="token keyword">public</span> abstract <span class="token keyword">void</span> <span class="token function">ROM</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> Computer <span class="token function">getComputer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> computer<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>3.具体建造者</strong> 这里只记录建造的步骤过程</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ComputerConcreteBuilder</span> <span class="token keyword">extends</span> <span class="token class-name">ComputerBuilder</span> <span class="token punctuation">{</span>
    @Override
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">CPU</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>computer<span class="token punctuation">.</span><span class="token function">setCPU</span><span class="token punctuation">(</span><span class="token string">"Intel I7"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    @Override
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">SSD</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>computer<span class="token punctuation">.</span><span class="token function">setSSD</span><span class="token punctuation">(</span><span class="token string">"三星固态硬盘"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    @Override
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">RAM</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>computer<span class="token punctuation">.</span><span class="token function">setRAM</span><span class="token punctuation">(</span><span class="token string">"8G内存"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    @Override
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">ROM</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>computer<span class="token punctuation">.</span><span class="token function">setROM</span><span class="token punctuation">(</span><span class="token string">"1T硬盘"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>4. 指挥者 也就是 我们组装人</strong> 需要获取到 <strong>具体建造者</strong> </p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * @author jian.li
 * @date 2020年 01月06日 16:25:18
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ComputerDirector</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">//获取当前建造者的指挥权</span>
    <span class="token keyword">private</span> ComputerBuilder computerBuilder<span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">//构造方法，直接获取建造者对象</span>
    <span class="token keyword">public</span> <span class="token function">ComputerDirector</span><span class="token punctuation">(</span>ComputerBuilder computerBuilder<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>computerBuilder <span class="token operator">=</span> computerBuilder<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">//指挥组装</span>
    <span class="token keyword">public</span> Computer <span class="token function">construct</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
       computerBuilder<span class="token punctuation">.</span><span class="token function">CPU</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
       computerBuilder<span class="token punctuation">.</span><span class="token function">RAM</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
       computerBuilder<span class="token punctuation">.</span><span class="token function">ROM</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
       computerBuilder<span class="token punctuation">.</span><span class="token function">SSD</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
       <span class="token keyword">return</span> computerBuilder<span class="token punctuation">.</span><span class="token function">getComputer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>5. 客户端调用</strong></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * @author jian.li
 * @date 2020年 01月06日 16:27:51
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ComputerClient</span> <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        ComputerBuilder builder <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ComputerConcreteBuilder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        ComputerDirector computerDirector <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ComputerDirector</span><span class="token punctuation">(</span>builder<span class="token punctuation">)</span><span class="token punctuation">;</span>
        Computer construct <span class="token operator">=</span> computerDirector<span class="token punctuation">.</span><span class="token function">construct</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>construct<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><img src="https://images.gitbook.cn/2606fb00-466e-11ea-815b-99042f14883a" alt="在这里插入图片描述"></p>
<h3 id="3-5-适配器模式"><a href="#3-5-适配器模式" class="headerlink" title="3.5 适配器模式"></a>3.5 适配器模式</h3><p><strong>适配器模式有分三类：</strong><br>1、类适配器模式（class adapter pattern）<br>2、对象适配器模式（object adapter pattern）<br>3、缺省适配器模式（default adapter pattern），也叫默认适配器模式、接口适配器模式</p>
<p><strong>角色：</strong><br>1、目标角色（target）：这是客户锁期待的接口。目标可以是具体的或抽象的类，也可以是接口<br>2、适配者角色（adaptee）：已有接口，但是和客户器期待的接口不兼容。<br>3、适配器角色（adapter）：将已有接口转换成目标接口。</p>
<h4 id="3-5-1-类适配器模式"><a href="#3-5-1-类适配器模式" class="headerlink" title="3.5.1 类适配器模式"></a>3.5.1 类适配器模式</h4><p><img src="https://images.gitbook.cn/75f63cc0-466e-11ea-8b8f-9189e02bc105" alt="在这里插入图片描述"><br>如上图，因为java没有类多继承，所以只能实现Target接口，而且Target只能是接口。Adapter实现了Target接口，继承了Adaptee类，Target.operation()实现为Adaptee.specificOperation()。<br><strong>需要适配的适配者：</strong></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">PowerAdaptee</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> int output <span class="token operator">=</span> <span class="token number">220</span><span class="token punctuation">;</span>
    <span class="token keyword">public</span> int <span class="token function">output220V</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"电源输出电压："</span><span class="token operator">+</span>output<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> output<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>定义适配接口 220V - 5V 接口转换</strong></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * @author jian.li
 * @date 2020年 01月07日 14:02:26
 */</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">PowerTarget</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> int <span class="token function">output5V</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>转换过程</strong></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * @author jian.li
 * @date 2020年 01月07日 14:05:09
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">PowerAdapter</span> <span class="token keyword">extends</span> <span class="token class-name">PowerAdaptee</span> <span class="token keyword">implements</span> <span class="token class-name">PowerTarget</span> <span class="token punctuation">{</span>
    @Override
    <span class="token keyword">public</span> int <span class="token function">output5V</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        int output <span class="token operator">=</span> <span class="token function">output220V</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"电源适配器开始工作，此时输出电压是："</span> <span class="token operator">+</span> output<span class="token punctuation">)</span><span class="token punctuation">;</span>
        output <span class="token operator">=</span> output <span class="token operator">/</span> <span class="token number">44</span><span class="token punctuation">;</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"电源适配器工作完成，此时输出电压是："</span> <span class="token operator">+</span> output<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> output<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>客户端调用</strong></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * @author jian.li
 * @date 2020年 01月07日 16:18:20
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TestClient</span> <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        PowerTarget powerTarget <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">PowerAdapter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        powerTarget<span class="token punctuation">.</span><span class="token function">output5V</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<h4 id="3-5-2-对象适配器"><a href="#3-5-2-对象适配器" class="headerlink" title="3.5.2 对象适配器"></a>3.5.2 对象适配器</h4><p>对象适配器与类适配器不同之处在于，类适配器通过继承来完成适配，对象适配器则是通过关联来完成，这里稍微修改一下 Adapter 类即可将转变为对象适配器。转化过程如下所示</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * @author jian.li
 * @date 2020年 01月07日 14:05:09
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">PowerAdapter</span> <span class="token keyword">implements</span> <span class="token class-name">PowerTarget</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> PowerAdaptee powerAdaptee<span class="token punctuation">;</span>
    <span class="token keyword">public</span> <span class="token function">PowerAdapter</span><span class="token punctuation">(</span>PowerAdaptee powerAdaptee<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>powerAdaptee <span class="token operator">=</span> powerAdaptee<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    @Override
    <span class="token keyword">public</span> int <span class="token function">output5V</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        int output <span class="token operator">=</span> powerAdaptee<span class="token punctuation">.</span><span class="token function">output220V</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"电源适配器开始工作，此时输出电压是："</span> <span class="token operator">+</span> output<span class="token punctuation">)</span><span class="token punctuation">;</span>
        output <span class="token operator">=</span> output <span class="token operator">/</span> <span class="token number">44</span><span class="token punctuation">;</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"电源适配器工作完成，此时输出电压是："</span> <span class="token operator">+</span> output<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> output<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><img src="https://images.gitbook.cn/94c421d0-466e-11ea-815b-99042f14883a" alt="在这里插入图片描述"></p>
<h4 id="3-5-3-缺省适配器模式（default-adapter-pattern）"><a href="#3-5-3-缺省适配器模式（default-adapter-pattern）" class="headerlink" title="3.5.3 缺省适配器模式（default adapter pattern）"></a>3.5.3 缺省适配器模式（default adapter pattern）</h4><p>当不需要全部实现接口提供的方法时，可以设计一个适配器抽象类实现接口，并为接口中的每个方法提供默认方法，抽象类的子类就可以有选择的覆盖父类的某些方法实现需求，它适用于一个接口不想使用所有的方法的情况。在java8后，接口中可以有default方法，就不需要这种缺省适配器模式了。接口中方法都设置为default，实现为空，这样同样同样可以达到缺省适配器模式同样的效果。<br><img src="https://images.gitbook.cn/a7850140-466e-11ea-b539-4302b67c89d7" alt="在这里插入图片描述"><br>目标角色</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">SampleOperation</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> abstract <span class="token keyword">void</span> <span class="token function">operation1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">public</span> abstract <span class="token keyword">void</span> <span class="token function">operation2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">public</span> abstract <span class="token keyword">void</span> <span class="token function">operation3</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">public</span> abstract <span class="token keyword">void</span> <span class="token function">operation4</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">public</span> abstract <span class="token keyword">void</span> <span class="token function">operation5</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>适配器角色</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> abstract <span class="token keyword">class</span> <span class="token class-name">DefaultAdapter</span> <span class="token keyword">implements</span> <span class="token class-name">SampleOperation</span><span class="token punctuation">{</span>

    @Override
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation1</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token punctuation">}</span>

    @Override
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token punctuation">}</span>

    @Override
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation3</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token punctuation">}</span>

    @Override
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation4</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token punctuation">}</span>

    @Override
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation5</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>这个是测试缺省适配器模式需要用到的类（Operator.java）：</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Operator</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> SampleOperation sampleOperation<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">addOperation</span><span class="token punctuation">(</span>SampleOperation sampleOperation<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>sampleOperation <span class="token operator">=</span> sampleOperation<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation1</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        sampleOperation<span class="token punctuation">.</span><span class="token function">operation1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        sampleOperation<span class="token punctuation">.</span><span class="token function">operation2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation3</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        sampleOperation<span class="token punctuation">.</span><span class="token function">operation3</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation4</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        sampleOperation<span class="token punctuation">.</span><span class="token function">operation4</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation5</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        sampleOperation<span class="token punctuation">.</span><span class="token function">operation5</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>测试类</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DefaultAdapterTest</span> <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>

        <span class="token comment" spellcheck="true">// 1、原来要实现所有操作类的操作</span>
        Operator operator1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Operator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        operator1<span class="token punctuation">.</span><span class="token function">addOperation</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">SampleOperation</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

            @Override
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation1</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

            @Override
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"操作2"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>

            @Override
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation3</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

            @Override
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation4</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

            @Override
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation5</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        operator1<span class="token punctuation">.</span><span class="token function">operation2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">// 2、使用缺省适配器只需要实现需要用到的接口方法</span>
        Operator operator2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Operator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        operator2<span class="token punctuation">.</span><span class="token function">addOperation</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">DefaultAdapter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

            @Override
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operation2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"操作2"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        operator2<span class="token punctuation">.</span><span class="token function">operation2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<h4 id="3-5-4-总结"><a href="#3-5-4-总结" class="headerlink" title="3.5.4 总结"></a>3.5.4 总结</h4><p>本文主要介绍了三种适配器模式，本质上是现有的不兼容的接口转换为需要的接口。</p>
<ul>
<li>类适配器模式，以继承现有类的方式转换。</li>
<li>对象适配器模式，以聚合对象实例的方式转换。</li>
<li>接口适配器模式，以实现接口的方式转换。</li>
</ul>
<p>适配器模式是在现有的类和系统都不易修改的情况下使用，在系统设计之初慎用适配器模式。</p>
<h3 id="3-6-代理模式"><a href="#3-6-代理模式" class="headerlink" title="3.6 代理模式"></a>3.6 代理模式</h3><p><strong>什么是代理模式？</strong><br>为其他对象提供一种代理，以控制对这个对象的访问。类似于中介商、12306 网站等。<br>代理对象在 <strong>客户端</strong> 和 <strong>目标对象</strong> 之间起到中介的作用。<strong>例如：</strong> 我们租房子为例，房东就是我们的目标对象，合同草拟、水电的结算等都是代理对象来做的，也就是中介，我们我们客户端跟代理类接触，<strong>代理类同时也增强了 目标对象 的功能</strong>。<br><img src="https://images.gitbook.cn/3f41a660-4d9e-11ea-bb35-2725b4649300" alt="在这里插入图片描述"></p>
<h4 id="3-6-1-代理模式的适用场景和优点"><a href="#3-6-1-代理模式的适用场景和优点" class="headerlink" title="3.6.1 代理模式的适用场景和优点"></a>3.6.1 代理模式的适用场景和优点</h4><ol>
<li>保护目标对象</li>
<li>增强目标对象</li>
</ol>
<p>以租房为例，我们与中介交流，基本见不到房东，对房东的一种保护。同时也可抽象理解中介的存在间接的增强了房东的向外租房能力。<br><strong>代理模式</strong> 的优缺点如下图所示：<br><img src="https://images.gitbook.cn/d9ed2e40-4d9f-11ea-bb35-2725b4649300" alt="在这里插入图片描述"></p>
<h4 id="3-6-2-代理模式的代码实现"><a href="#3-6-2-代理模式的代码实现" class="headerlink" title="3.6.2 代理模式的代码实现"></a>3.6.2 代理模式的代码实现</h4><p><img src="https://images.gitbook.cn/bc366910-4da0-11ea-a325-5b2189984a9b" alt="在这里插入图片描述"><br> <strong>举例：</strong> 这里我们以 <strong>订单的分库保存</strong> 为例。根据订单的末尾数与 2 取模，把该订单保存到相应的库中。<br> 前提：以 MVC 模式，创建 订单实体、订单Dao、订单Service。</p>
<pre class=" language-javascript"><code class="language-javascript"> <span class="token comment" spellcheck="true">/**
 * 订单实体类
 * @author lijian
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Order</span> <span class="token punctuation">{</span>

    <span class="token comment" spellcheck="true">/** 订单信息 */</span>
    <span class="token keyword">private</span> Object orderInfo<span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">/** 订单 用户Id */</span>
    <span class="token keyword">private</span> Integer userId<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">// getter setter 省略</span>
<span class="token punctuation">}</span></code></pre>
<pre class=" language-javascript"><code class="language-javascript"> <span class="token comment" spellcheck="true">/**
 * 订单 Dao 层
 * @author lijian
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">IOrderDaoImpl</span> <span class="token keyword">implements</span> <span class="token class-name">IOrderDao</span> <span class="token punctuation">{</span>

    @Override
    <span class="token keyword">public</span> int <span class="token function">insert</span><span class="token punctuation">(</span>Order order<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"向数据库中添加一条订单成功"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">interface</span> <span class="token class-name">IOrderDao</span><span class="token punctuation">{</span>
    int <span class="token function">insert</span><span class="token punctuation">(</span>Order order<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<pre class=" language-javascript"><code class="language-javascript"> <span class="token comment" spellcheck="true">/**
 * 订单 Service 层
 * @author lijian
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">IOrderServiceImpl</span> <span class="token keyword">implements</span> <span class="token class-name">IOrderService</span>  <span class="token punctuation">{</span>

    <span class="token keyword">private</span> IOrderDao iOrderDao<span class="token punctuation">;</span>

    @Override
    <span class="token keyword">public</span> int <span class="token function">saveOrder</span><span class="token punctuation">(</span>Order order<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">// Spring 中 通过 @Autowire 自动注入，这里我们直接 new 了</span>
        iOrderDao <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">IOrderDaoImpl</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> iOrderDao<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</span>order<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">interface</span> <span class="token class-name">IOrderService</span> <span class="token punctuation">{</span>

    int <span class="token function">saveOrder</span><span class="token punctuation">(</span>Order order<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p> <strong>代理模式第一种  —— 静态代理</strong></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * OrderService 的 静态代理类
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">OrderServiceStaticProxy</span> <span class="token keyword">implements</span> <span class="token class-name">IOrderService</span>  <span class="token punctuation">{</span>

    <span class="token keyword">private</span> IOrderService iOrderService<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token function">OrderServiceStaticProxy</span><span class="token punctuation">(</span>IOrderService iOrderService<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>iOrderService <span class="token operator">=</span> iOrderService<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    @Override
    <span class="token keyword">public</span> int <span class="token function">saveOrder</span><span class="token punctuation">(</span>Order order<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">// 增强 之前做什么</span>
        <span class="token function">beforeMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        iOrderService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">IOrderServiceImpl</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        int userId <span class="token operator">=</span> order<span class="token punctuation">.</span><span class="token function">getUserId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        int dbRouter <span class="token operator">=</span> userId <span class="token operator">%</span> <span class="token number">2</span> <span class="token punctuation">;</span>
        int result <span class="token operator">=</span> iOrderService<span class="token punctuation">.</span><span class="token function">saveOrder</span><span class="token punctuation">(</span>order<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">// 增强 之后做什么</span>
        <span class="token function">afterMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> result<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">afterMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">beforeMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

<span class="token punctuation">}</span></code></pre>
<p>模拟 Controller 层静态代理的使用：</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * 模拟Controller
 * @author jian.li
 * @date 2020年 01月07日 17:03:57
 */</span>
 <span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">AppController</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> IOrderService iOrderService<span class="token punctuation">;</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">saveOrder</span><span class="token punctuation">(</span>Order order<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">//一般是 @Autowire</span>
        iOrderService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">IOrderServiceImpl</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        OrderServiceStaticProxy orderServiceStaticProxy <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">OrderServiceStaticProxy</span><span class="token punctuation">(</span>iOrderService<span class="token punctuation">)</span><span class="token punctuation">;</span>
        int result <span class="token operator">=</span> orderServiceStaticProxy<span class="token punctuation">.</span><span class="token function">saveOrder</span><span class="token punctuation">(</span>order<span class="token punctuation">)</span><span class="token punctuation">;</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>静态代理总结:<br><img src="https://images.gitbook.cn/60ff8800-4db5-11ea-9765-e162b5bc6395" alt="在这里插入图片描述"><br> <strong>代理模式第二种  —— 动态代理</strong></p>
<p><strong>动态代理</strong> 是利用 JDK 的API中的 Proxy 类实现的，通过反射动态的在内存中构建代理对象。</p>
<p><img src="https://images.gitbook.cn/2fb1adc0-4e5d-11ea-8532-814baa40f153" alt="在这里插入图片描述"></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">// java.lang.reflect.Proxy</span>
<span class="token keyword">static</span> Object <span class="token function">newProxyInstance</span><span class="token punctuation">(</span>ClassLoader loader<span class="token punctuation">,</span> Class<span class="token operator">&lt;</span><span class="token operator">?</span><span class="token operator">></span><span class="token punctuation">[</span><span class="token punctuation">]</span> interfaces<span class="token punctuation">,</span>InvocationHandler h <span class="token punctuation">)</span></code></pre>
<p>注意该方法是在Proxy类中是静态方法,且接收的三个参数依次为:<br><img src="https://images.gitbook.cn/dc22e1a0-4e5d-11ea-a2fb-85c45bbaa11c" alt="在这里插入图片描述"></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * 创建动态的代理对象
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">OrderServiceDynamicProxy</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> IOrderService iOrderService<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token function">OrderServiceDynamicProxy</span><span class="token punctuation">(</span>IOrderService iOrderService<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>iOrderService <span class="token operator">=</span> iOrderService<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> Object <span class="token function">getProxyInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        Object object <span class="token operator">=</span> Proxy<span class="token punctuation">.</span><span class="token function">newProxyInstance</span><span class="token punctuation">(</span>iOrderService<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                iOrderService<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getInterfaces</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">InvocationHandler</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    @Override
                    <span class="token keyword">public</span> Object <span class="token function">invoke</span><span class="token punctuation">(</span>Object proxy<span class="token punctuation">,</span> Method method<span class="token punctuation">,</span> Object<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> throws Throwable <span class="token punctuation">{</span>
                        <span class="token function">beforeMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token comment" spellcheck="true">//运用反射执行目标对象方法</span>
                        Object returnValue <span class="token operator">=</span> method<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>iOrderService<span class="token punctuation">,</span> args<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token function">afterMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">return</span> returnValue<span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>
                <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> object<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">afterMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">beforeMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>模拟 Controller 层动态代理的使用：</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">AppController2</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> IOrderService iOrderService<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">saveOrder</span><span class="token punctuation">(</span>Order order<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">//一般是 @Autowire</span>
        iOrderService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">IOrderServiceImpl</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        OrderServiceDynamicProxy orderServiceDynamicProxy <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">OrderServiceDynamicProxy</span><span class="token punctuation">(</span>iOrderService<span class="token punctuation">)</span><span class="token punctuation">;</span>
        IOrderService proxyInstance <span class="token operator">=</span> <span class="token punctuation">(</span>IOrderService<span class="token punctuation">)</span> orderServiceDynamicProxy<span class="token punctuation">.</span><span class="token function">getProxyInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        int result <span class="token operator">=</span> proxyInstance<span class="token punctuation">.</span><span class="token function">saveOrder</span><span class="token punctuation">(</span>order<span class="token punctuation">)</span><span class="token punctuation">;</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p> <strong>代理模式第三种  —— Cglib代理(基于继承的方式实现)</strong><br>　　<br>实现静态或者动态代理的要求目标对象必须实现接口。但是往往有些类，它是单独存在的，他没有继承任何抽象类或者实现任何接口。如果单一对象想要实现代理模式的话。这种就是第三种代理模式—— <strong>Cglib代理</strong>。<br><img src="https://images.gitbook.cn/8ebab890-4e60-11ea-a2fb-85c45bbaa11c" alt="在这里插入图片描述"><br>话不多说，我们码起来，还是以订单为例。</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * 目标对象,没有实现任何接口
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">OrderService</span> <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">saveOrder</span><span class="token punctuation">(</span>Order order<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">// 这里直接调用 orderDao 把 order 存入到库中。</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * Cglib子类代理工厂
 * 对UserDao在内存中动态构建一个子类对象
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">CglibProxy</span> <span class="token keyword">implements</span> <span class="token class-name">MethodInterceptor</span><span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">//维护目标对象</span>
    <span class="token keyword">private</span> Object orderService<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token function">CglibProxy</span><span class="token punctuation">(</span>Object orderService<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>orderService <span class="token operator">=</span> orderService<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">//给目标对象创建一个代理对象</span>
    <span class="token keyword">public</span> Object <span class="token function">getProxyInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">//1.工具类</span>
        Enhancer en <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Enhancer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">//2.设置父类</span>
        en<span class="token punctuation">.</span><span class="token function">setSuperclass</span><span class="token punctuation">(</span>orderService<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">//3.设置回调函数</span>
        en<span class="token punctuation">.</span><span class="token function">setCallback</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">//4.创建子类(代理对象)</span>
        <span class="token keyword">return</span> en<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span> 

    @Override
    <span class="token keyword">public</span> Object <span class="token function">intercept</span><span class="token punctuation">(</span>Object obj<span class="token punctuation">,</span> Method method<span class="token punctuation">,</span> Object<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">,</span> MethodProxy proxy<span class="token punctuation">)</span> throws Throwable <span class="token punctuation">{</span>
        <span class="token function">beforeMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        Object returnValue <span class="token operator">=</span> method<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>orderService<span class="token punctuation">,</span> args<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">afterMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> returnValue<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>模拟 Controller 层  Cglib 的使用：</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">AppController2</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> IOrderService iOrderService<span class="token punctuation">;</span>


    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">saveOrder</span><span class="token punctuation">(</span>Order order<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">//一般是 @Autowire</span>
        iOrderService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">IOrderServiceImpl</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        代理对象
        IOrderService proxy <span class="token operator">=</span> <span class="token punctuation">(</span>IOrderService <span class="token punctuation">)</span><span class="token keyword">new</span> <span class="token class-name">ProxyFactory</span><span class="token punctuation">(</span>iOrderService<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getProxyInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">//执行代理对象的方法</span>
        int result <span class="token operator">=</span> proxy<span class="token punctuation">.</span><span class="token function">saveOrder</span><span class="token punctuation">(</span>order<span class="token punctuation">)</span><span class="token punctuation">;</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<h4 id="3-6-3-代理模式的总结"><a href="#3-6-3-代理模式的总结" class="headerlink" title="3.6.3 代理模式的总结"></a>3.6.3 代理模式的总结</h4><p><img src="https://images.gitbook.cn/5d9eef40-4e62-11ea-ae10-63f5622e4259" alt="在这里插入图片描述"></p>
<h3 id="3-7-外观模式"><a href="#3-7-外观模式" class="headerlink" title="3.7 外观模式"></a>3.7 外观模式</h3><h4 id="3-7-1-什么是外观模式？"><a href="#3-7-1-什么是外观模式？" class="headerlink" title="3.7.1 什么是外观模式？"></a>3.7.1 什么是外观模式？</h4><p><strong>外观模式</strong> : 隐藏系统的复杂性，并向客户端提供了一个客户端可以访问系统的接口。这种类型的设计模式属于结构型模式，它向现有的系统添加一个接口，来隐藏系统的复杂性。还称之为：门面模式。</p>
<h4 id="3-7-2-外观模式的适用场景和优点？"><a href="#3-7-2-外观模式的适用场景和优点？" class="headerlink" title="3.7.2 外观模式的适用场景和优点？"></a>3.7.2 外观模式的适用场景和优点？</h4><p>一图明白一切。<br><img src="https://images.gitbook.cn/5b4d92f0-4e67-11ea-a847-a5aa0d0597f8" alt="在这里插入图片描述"></p>
<h4 id="3-7-3-外观模式的实现"><a href="#3-7-3-外观模式的实现" class="headerlink" title="3.7.3 外观模式的实现"></a>3.7.3 外观模式的实现</h4><blockquote>
<p>以 我们拿出手机 解锁，给李萍打电话为例。</p>
</blockquote>
<p>以面向对象的设计思路，具体实现步骤应该如下所示：</p>
<ol>
<li>人拿出手机</li>
<li>手机解锁</li>
<li>手机按照号码拨打电话给李萍</li>
</ol>
<p>需要两个类，一个是 Person 类，另一个是 Phone 类。</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Person</span> <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">takePhone</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"从裤子中拿出手机来。"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<pre><code>public class Phone {

    public void clear(){
        System.out.println("手机解锁.....");
    }

    public void tell(){
        System.out.println("拨打电话给李萍");
    }
}
</code></pre><p>如果没有用外观模式时，我们需要这几步能打电话。</p>
<pre><code>public class Test {

    public static void main(String[] args) {
        Person person = new Person();
        Phone phone = new Phone();
        person.takePhone();
        phone.clear();
        phone.tell();
    }
}</code></pre><p>如果用外观模式时，隐藏系统的复杂性，向客户端提供一个简单的接口。</p>
<pre><code>public class TellFacade {

    /**
     * 提供一个接口，系统的复杂性
     */
    public void tell(){
        Person person = new Person();
        Phone phone = new Phone();
        person.takePhone();
        phone.clear();
        phone.tell();
    }
}</code></pre><pre><code>public class FacedeTest {

    public static void main(String[] args) {
        TellFacade tellFacade = new TellFacade();
        tellFacade.tell();
    }
}
</code></pre><script>
        document.querySelectorAll('.github-emoji')
          .forEach(el => {
            if (!el.dataset.src) { return; }
            const img = document.createElement('img');
            img.style = 'display:none !important;';
            img.src = el.dataset.src;
            img.addEventListener('error', () => {
              img.remove();
              el.style.color = 'inherit';
              el.style.backgroundImage = 'none';
              el.style.background = 'none';
            });
            img.addEventListener('load', () => {
              img.remove();
            });
            document.body.appendChild(img);
          });
      </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://lijiangit.gitee.io" rel="external nofollow noreferrer">Lijian</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://lijiangit.gitee.io/2020/03/06/she-ji-mo-shi/">http://lijiangit.gitee.io/2020/03/06/she-ji-mo-shi/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="http://lijiangit.gitee.io" target="_blank">Lijian</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/java/">
                                    <span class="chip bg-color">java</span>
                                </a>
                            
                                <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">
                                    <span class="chip bg-color">设计模式</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.jpg" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: '6434a7e26807850fb267',
        clientSecret: 'bd623169943e782692836cb4e408422299890552',
        repo: 'https://github.com/lijian69/lijian69.github.io.git',
        owner: 'lijian69',
        admin: "lijian69",
        id: '2020-03-06T09-33-54',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2020/03/06/leetcode/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/13.jpg" class="responsive-img" alt="LeetCode 编程进阶">
                        
                        <span class="card-title">LeetCode 编程进阶</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            LeetCode收录了许多互联网公司的算法题目，被称为刷题神器。如果是为了面试，刷Leetcode还是很重要的。一是提高对简单题的熟悉程度，有一些听起来很轻松的题目，比如旋转矩阵，写过一次和没写过的临场表现可能会有很大的差距；二是可以见识一
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-06
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%AE%97%E6%B3%95/" class="post-category">
                                    算法
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/java/">
                        <span class="chip bg-color">java</span>
                    </a>
                    
                    <a href="/tags/LeetCode/">
                        <span class="chip bg-color">LeetCode</span>
                    </a>
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/03/06/pai-xu-suan-fa/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/21.jpg" class="responsive-img" alt="基于 Java 的排序算法">
                        
                        <span class="card-title">基于 Java 的排序算法</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            排序算法，即通过特定的算法因式将一组或多组数据按照既定模式进行重新排序。这种新序列遵循着一定的规则，体现出一定的规律，因此，经处理后的数据便于筛选和计算，大大提高了计算效率。对于排序，我们首先要求其具有一定的稳定性，


本节主要是对八大排
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-03-06
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%AE%97%E6%B3%95/" class="post-category">
                                    算法
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/java/">
                        <span class="chip bg-color">java</span>
                    </a>
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2020</span>
            <a href="http://lijiangit.gitee.io" target="_blank">Lijian</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">25.3k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://gitee.com/LiJianGit" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1326369406@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1326369406" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1326369406" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>


</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
